//
//  SLHttpTool.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/5.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import UIKit
import CoreLocation
import MBProgressHUD


struct SLHttpTool{
    static var  headers: HTTPHeaders = [
        "Content-Type" : "application/x-www-form-urlencoded"
    ]
}

extension SLHttpTool {
    /// 拼接其他参数
    static func StringJoinParameter(url:String,dic:Dictionary<String, Any>? = nil) -> String {
        var temPath = ""
        if url.contains("http") {
            temPath = url
        }else{
            let pre:String = SLAPIConfig.rootPath
            var baseurl = SLAPIConfig.baseURL
            if let string = __valueForKey(key: "baseUrl") as? String{
                baseurl = string
            }
            temPath = "\(baseurl)\(pre)\(url)"
        }
        let none = SLTool.getVersion()
        let classic = SLTool.getDeviceModel()
        let gaze = SLKeychain.getIDFV()
        let hair = SLUserAccount.default.hair
        let symbolically = SLKeychain.getIDFA()
        let splendour = SLUserAccount.default.sessionId
        let providing = SLTool.getSystemVersion()
        var bodyDic = Dictionary<String, Any>()
        if let dic = dic{
            for item in dic {
                bodyDic.updateValue(item.value, forKey: item.key)
            }
        }
        bodyDic.updateValue(none, forKey:"none" )
        bodyDic.updateValue(classic, forKey:"classic" )
        bodyDic.updateValue(gaze, forKey:"gaze" )
        bodyDic.updateValue(hair, forKey: "hair")
        bodyDic.updateValue(symbolically, forKey:"symbolically" )
        bodyDic.updateValue(splendour, forKey:"splendour" )
        bodyDic.updateValue(providing, forKey:"providing" )
        var baseUrl = temPath + "?"
        var params:[String] = []
        for dic in bodyDic{
            params.append("\(dic.key)=\(dic.value)")
        }
        baseUrl = baseUrl + params.joined(separator: "&")

        return baseUrl
    }
    
    static func AsyncReportData(path:String,params:[String:Any]? = [:],image: UIImage? = nil,fileName:String? = "narrowMegalithic",method:HTTPMethod? = .post,target:Any?,finishCallBack:@escaping (_ responseData:JSON,_ success:Bool,_ msg:String,_ code:String)->())->Void {
        var temPath = ""
        temPath = StringJoinParameter(url: path)
        
        do {
            let request = try URLRequest(url: temPath, method: method ?? .post, headers: headers)
            AF.upload(multipartFormData: { partFormData in
                if image != nil {
                    guard let data = image!.jpegData(compressionQuality: 0.5) else { return  }
                    partFormData.append(data, withName: fileName!,fileName: _date_timestamp_string() + ".jpg",mimeType: "image/jpg")
                }
                for (key, value) in params! {
                    if let v = value as? [Any] {
                        // 将数组转换为Data
                        if let jsonData = try? JSONSerialization.data(withJSONObject: v, options: []) {
                            partFormData.append(jsonData, withName: key)
                        }
                    }else{
                        partFormData.append(("\(value)".data(using: .utf8)!), withName: key)
                    }
                }
            }, with: request).response{ (response) in
                MBProgressHUD.hideHUD()
                if target == nil {print("控制器已释放");return}
                print("接口信息:\(temPath) \n response:\(response.result)")
                
                responseData(response: response, finishCallBack: finishCallBack)
            }
        } catch  {
            MBProgressHUD.hideHUD()
        }
    }
    static func responseData(response:AFDataResponse<Data?>, finishCallBack:@escaping (_ responseData:JSON,_ success:Bool,_ msg:String,_ code:String)->())->Void{
        switch response.result {
            case .success(let value):
            let json = JSON(value)
            let code:String =  json["sculptor"].stringValue
            let msg:String = json["naturalistic"].stringValue
            var succeed:Bool = false

            if(code == "0"||code == "00"){
                succeed = true
            }else if code == "-2" {
                GoToLoginVC()
            }else{
                MBProgressHUD.showError(error: msg)
            }
            finishCallBack(json,succeed,msg,code)
            case .failure(let error):
                print(error)
                finishCallBack(JSON(error.localizedDescription),false,error.localizedDescription,"10010")
            }
    }
    /// 上报风控埋点
    /// - Parameters:
    ///
    ///   - mahathat: 1=注册 2=证件类型 3=正面 4=自拍 5=个人信息 6=工作信息 7=联系人 8=绑卡 9=开始审贷 10=结束审贷
    ///   - extended: 用户申贷订单号
    ///   - buddharupa: idfv
    ///   - indra: 纬度
    ///   - weapon: 经度
    ///   - thais: 开始时间
    ///   - blocks: 结束时间
    ///   - target: 当前控制器··
    ///   - finishCallBack: 回调
    /// - Returns: void
    static func AsyncUploadData(mahathat:String? = "",extended:String? = "",politics:String? = "",indra:Int? = 0,weapon:Int? = 0,thais:String? = "",blocks:String? = "", target:Any?,finishCallBack:@escaping (_ responseData:JSON,_ success:Bool,_ msg:String,_ code:String)->())->Void {
        var params:[String: Any] = [:]
        params["stairs"] = "2"
        params["mahathat"] = mahathat
        params["extended"] = extended
        let blocks = "\(Date().timeIntervalSince1970)"
        params["blocks"] = blocks
        params["thais"] = thais
        if thais!.isEmpty {
            params["thais"] = blocks
        }
        params["laterite"] = SLKeychain.getIDFA()
        params["cella"] = SLKeychain.getIDFV()
        params["indra"] = __valueForKey(key: "latitude")
        params["weapon"] = __valueForKey(key: "longitude")
        AsyncPointData(path: "/satisfies/greece",params: params, target: target, finishCallBack: finishCallBack)
        
    }
    static func responseUploadData(response:AFDataResponse<Data?>, finishCallBack:@escaping (_ responseData:JSON,_ success:Bool,_ msg:String,_ code:String)->())->Void{
        switch response.result {
            case .success(let value):
            let json = JSON(value)
            let code:String =  json["sculptor"].stringValue
            let msg:String = json["naturalistic"].stringValue
            var succeed:Bool = false

            if(code == "0"||code == "00"){
                succeed = true
            }else if code == "-2" {
                GoToLoginVC()
            }else{
                
            }
            finishCallBack(json,succeed,msg,code)
            case .failure(let error):
                print(error)
                finishCallBack(JSON(error.localizedDescription),false,error.localizedDescription,"10010")
            }
    }
    static func uploadDevData(){
        var cob:[String: String] = [:]
        var lopburi:[String: String] = [:]
        var sukhothai:[String: String] = [:]
        var complexes:[String: String] = [:]
        var prangs:[String: String] = [:]
        var sumatra:[String: Any] = [:]
        cob["corn"] = Helper.getNewFreeSize()
        cob["measure"] = Helper.getTotalDiskSize()
        cob["arun"] = Helper.getTotalMemorySize()
        cob["bangkok"] = Helper.getAvailableMemorySize()
        
        lopburi["categories"] = SLTool.getDeviceBatteryLevel()
        lopburi["falls"] = SLTool.getDeviceBatterySratus()
        
        sukhothai["masters"] = SLTool.getDeviceSystemVersion()
        sukhothai["collapsed"] = SLTool.getDeviceModel()
        sukhothai["thom"] = SLTool.getDeviceName()

        complexes["rekha"] = "0"
        complexes["resembled"] = "0"
        if SLTool.isJailBroken(){
            complexes["resembled"] = "1"
        }

        let timeZone = TimeZone.current
        prangs["inclusion"] = timeZone.identifier
        prangs["buddharupa"] = SLKeychain.getIDFV()
        prangs["fifth"] = Locale.current.languageCode
        prangs["chaiwatthanaram"] = SLTool.getNetworkType()
        prangs["suggested"] = SLKeychain.getIDFA()
        
        var mon:[String:Any] = [:]
        if let wifiInfo = SLTool.getCurrentWiFiInfo(){
            mon["funan"] = wifiInfo.BSSID
            mon["suthat"] = wifiInfo.SSID
        }else{
            
        }
        sumatra["mon"] = mon

        var params:[String:Any] = [:]
        params["cob"] = cob
        params["lopburi"] = lopburi
        params["sukhothai"] = sukhothai
        params["complexes"] = complexes
        params["prangs"] = prangs
        params["sumatra"] = sumatra
        if let jsonData = try? JSONSerialization.data(withJSONObject: params, options: []) {
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                SLHttpTool.AsyncReportData(path: "/satisfies/probable",params: ["wavelets":jsonString], target: self) { responseCall, success, msg, code in
                    
                }
            }
        }
    }

    static func AsyncPointData(path:String,params:[String:Any]?,method:HTTPMethod? = .post,target:Any?,finishCallBack:@escaping (_ responseData:JSON,_ success:Bool,_ msg:String,_ code:String)->())->Void {

        var temPath = ""
        temPath = StringJoinParameter(url: path)
        do {
            let request = try URLRequest(url: temPath, method: method ?? .post, headers: headers)
            
            AF.upload(multipartFormData: { partFormData in
            
                for (key, value) in params! {
                    if let v = value as? [Any] {
                        // 将数组转换为Data
                        if let jsonData = try? JSONSerialization.data(withJSONObject: v, options: []) {
                            partFormData.append(jsonData, withName: key)
                        }
                    }else{
                        partFormData.append(("\(value)".data(using: .utf8)!), withName: key)
                    }
                }
            }, with: request).response{ (response) in
                if target == nil {print("控制器已释放");return}
                print("接口信息:\(temPath) \n response:\(response.result)")
                responseUploadData(response: response, finishCallBack: finishCallBack)
            }
        } catch  {
            
        }
    }
}
